<template>
	<u-modal v-model="show" ref="uModal" :show-cancel-button="isShowCancel" :show-confirm-button="isShowConfirm" confirm-text="升级" title="发现新版本" @cancel="cancel" @confirm="toUpdata" :async-close="true">
		<view class="u-update-content">
			<template  v-if="isShowProgress">
				<view class="j-d-progress">{{progress}}</view>
			</template>
			<template v-else>
				<rich-text :nodes="content"></rich-text>
			</template>
		</view>
	</u-modal>
</template>

<script>
	export default {
		data() {
			return {
				show: false,
				isShowCancel: false,
				isShowProgress: false,
				isShowConfirm: true,
				content: '',
				appFilePath: '',
				packageUrl: '',
				progress: '',
				isUpdate: 0
			}
		},
		onReady() {
			this.show = true;
			this.postFindNewVersionInfo();
		},
		onBackPress() {
			if(this.isUpdate == 1){
				return true;  
			}else{
				return false;  
			}
		},
		methods: {
			// 查询更新信息
			postFindNewVersionInfo(){
				this.$u.api
					.postFindNewVersionInfo({
						terminalType: 'Android'
					})
					.then(res => {
						console.log(res);
						// 判断是否强制更新
						this.isUpdate = res.data.isUpdate;
						if(res.data.isUpdate == 1){
							this.isShowCancel = false;
						}else{
							this.isShowConfirm = true;
						}
						// 更新内容
						this.content = res.data.updateContext;
						// 文件下载地址
						this.packageUrl = res.data.packageUrl;
					})
					.catch(err => {
						console.log(err);
					});
			},
			// 去更新
			toUpdata() {
				if (!this.appFilePath) {
					const downloadTask = uni.downloadFile({
						url: this.packageUrl,
						success: res => {
							console.log(res);
							if (res.statusCode === 200) {
								this.appFilePath = res.tempFilePath;
								plus.runtime.install(res.tempFilePath);
							}
						}
					});
					downloadTask.onProgressUpdate(res => {
						console.log(res.progress)
						this.isShowProgress = true;
						this.progress = res.progress + '%';
						if(res.progress == 100){
							this.$refs.uModal.clearLoading();
						}
					});
				} else {
					this.$refs.uModal.clearLoading();
					plus.runtime.openFile(this.appFilePath);
				}
			},
			cancel() {
				this.closeModal();
			},
			closeModal() {
				uni.navigateBack();
			}
		}
	}
</script>

<style scoped lang="scss">
	
	.j-d-progress{
		text-align: center;
		font-size: 40rpx;
		color: #000000;
	}
	
	.u-full-content {
		background-color: #00C777;
	}
	
	.u-update-content {
		font-size: 26rpx;
		color: $u-content-color;
		line-height: 1.7;
		padding: 30rpx;
	}
</style>
